package com.gin.monitor.agg.utils;

/**
 * @author gin
 * @date 2021/4/1
 */
public class HashUtils {

    /**
     * 32位 质数
     */
    static final int FNV_PRIME = 16777619;
    /**
     * 初始的哈希值
     */
    static final int OFFSET_BASIS = -2128831035;

    /**
     * 改进的32位FNV算法1
     * 质数: 32 bit FNV_prime = 2^24 + 2^8 + 0x93 = 16777619
     * 种子: 32 bit offset_basis = 2166136261L = -2128831035
     * {@link cn.hutool.core.util.HashUtil#fnvHash}
     *
     * @param key 字符串
     * @return hash结果(正整数: & 0x7FFFFFFF)
     */
    public static int fnvHash(String key) {
        int hash = OFFSET_BASIS;
        for (int i = 0; i < key.length(); i++) {
            hash = (hash ^ key.charAt(i)) * FNV_PRIME;
        }
        hash += hash << 13;
        hash ^= hash >> 7;
        hash += hash << 3;
        hash ^= hash >> 17;
        hash += hash << 5;
        //正数 及 负数
        //return hash
        //转正数
        return (hash & 0x7FFFFFFF);
    }

}
